
/****
 * Copyright (C) 2006 dNux Team
 *                                                            ****
 * This program is free software; you can redistribute it and/or *
 * modify under the terms of the GNU General Public License as   *
 * published by the Free Software Foundation;                    *
 * either version 2 of the License.                              *
 *                                                               *
 * This program is distributed in the hope that it will be       *
 * useful, but WITHOUT ANY WARRANTY; without even the implied    *
 * warranty of without even the implied waranty of               *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.          *
 * See the GNU General Public License for more details.          *
 *                                                               *
 * You should have received a copy of the                        *
 * GNU General Public License                                    *
 * along with this program; if not, write to the                 *
 * Free Software Foundation, Inc.,                               *
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA. *
 *                                                               *
 ****                                                         ****/

#include "dcore.h"

void
d_option_parse(d_option_t *options, int *argc, char ***argv, d_error_t **error)
{
  int i, j;
  char **old = NULL, **new = NULL;
  d_bool_t found;
  
  old = *argv;
  new = d_argv_new();
  d_argv_add(&new, old[0]);

  for(i=1; old[i]; i++) {
    found = d_false;

    for(j=0;  options[j].long_name; j++) {
      if (! strcmp("-h", old[i]) ||
	  ! strcmp("--help", old[i])) {
	d_option_help(options);
	exit(EXIT_FAILURE);
      }

      if (! strcmp(options[j].long_name, old[i]) ||
	  ! strcmp(options[j].short_name, old[i])) {
	found = d_true;
	switch(options[j].type) {
	case D_OPTION_STRING:
	  if (d_argv_length(old) > i + 1) {
	    *((char **)options[j].data) = old[i+1];
	    i++;
	  }
	  break;
	case D_OPTION_INTEGER:
	  if (d_argv_length(old) > i + 1) {
	    *((int *) options[j].data) = atoi(old[i+1]);
	    i++;
	  }
	  break;
	case D_OPTION_VOID:
	  *((d_bool_t *)options[j].data) = d_true;
	  break;
	}
      }
    }
    if (! found) {
      d_argv_add(&new, old[i]);
    }
  }
  *argv = new;
  *argc = d_argv_length(new);
}

void
d_option_help(d_option_t *options)
{
  int i;

  if (options==NULL)
    goto error;

  fprintf(stderr, " -- help --\n");
  for (i=0; options[i].long_name; i++) {
    fprintf(stderr, "%s ", options[i].long_name);
    
    if (options[i].short_name) {
      fprintf(stderr, "%s ", options[i].short_name);
    }
    else {
      fprintf(stderr, "- ");
    }

    fprintf(stderr, "%s\n", options[i].help);    
  }

 error:
  return;
}
